﻿using System;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;
using Omu.ValueInjecter;

namespace Omu.AwesomeDemo.Infra.Builder
{
    public class NullIntToEntity : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            return c.SourceProp.Name == c.TargetProp.Name
                   && c.SourceProp.Type == typeof(int?)
                   && c.TargetProp.Type.IsSubclassOf(typeof(Entity));
        }

        protected override object SetValue(ConventionInfo c)
        {
            if (c.SourceProp.Value == null) return null;
            var id = ((int?)c.SourceProp.Value).Value;

            dynamic repo = IoC.Resolve(typeof(IRepo<>).MakeGenericType(c.TargetProp.Type));

            return repo.Get(id); 
        }
    }
}